<?php
/**
 * Created by PhpStorm.
 * User: kavinga
 * Date: 1/15/14
 * Time: 3:57 PM
 */

namespace Cf\Mvc\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\Mvc\MvcEvent;

class Action extends AbstractActionController
{

    protected $authService;
    protected $storage;

    public function onDispatch(MvcEvent $e)
    {
        $resultResponse = $this->construct();
        if (!empty($resultResponse)) {
            return $resultResponse;
        }

        $resultResponse = $this->init();
        if (!empty($resultResponse)) {
            return $resultResponse;
        }

        return parent::onDispatch($e);
    }

    public function init()
    {

    }

    protected function construct()
    {
        $routeName = $this->getRouteMatch()->getMatchedRouteName();


        if ($this->getFrontAuthService()->hasIdentity()) {
            if (in_array($routeName, array('guest', 'home'))) {
                return $this->redirect()->toRoute('user', array('redirect' => base64_encode($this->getRequest()->getRequestUri())));
            }

        } else {
            if (!in_array($routeName, array('guest',))) {
                return $this->redirect()->toRoute('guest', array('redirect' => base64_encode($this->getRequest()->getRequestUri())));
            }
        }

    }

    public function getFrontAuthService()
    {
        if (!$this->authService) {
            $this->authService = $this->getServiceLocator()
                ->get('AuthFront');
        }

        return $this->authService;
    }

    public function getBackAuthService()
    {
        if (!$this->authService) {
            $this->authService = $this->getServiceLocator()
                ->get('AuthBack');
        }

        return $this->authService;
    }

    public function getFrontSessionStorage()
    {
        if (!$this->storage) {
            $this->storage = $this->getServiceLocator()
                ->get('AuthStorageFront');
        }

        return $this->storage;
    }

    public function getBackSessionStorage()
    {
        if (!$this->storage) {
            $this->storage = $this->getServiceLocator()
                ->get('AuthStorageBack');
        }

        return $this->storage;
    }

    public function getRouteMatch()
    {
        if (empty($this->routeMatch)) {
            $this->routeMatch = $this->getEvent()->getRouteMatch();
        }

        return $this->routeMatch;
    }
}